import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Index from '../views/Index.vue'
import User from '../views/sys/User.vue'
import Role from '../views/sys/Role.vue'
import Menu from '../views/sys/Menu.vue'

import axios from "../axios";
import store from "../store"
import el from "element-ui/src/locale/lang/el";

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'Home',
        redirect: '/index',  // 默认重定向到首页
        component: Home,
        children: [
            {
                path: '/index',
                name: 'Index',
                meta: {
                    title: "首页",
                    requiresAuth: false  // 游客也可访问
                },
                component: Index
            },
            {
                path: '/userCenter',
                name: 'UserCenter',
                meta: {
                    title: "个人中心",
                    requiresAuth: true  // 添加此行来标志访问此路由需要授权
                },
                component: () => import('@/views/UserCenter.vue')
            },
            {
                path: '/login',
                name: 'Login',
                component: () => import('@/views/Login.vue')
            },
            {
                path:'/enroll',
                name:'Enroll',
                meta: {
                    title: "注册",
                    requiresAuth: false
                },
                component: () => import('@/views/Enroll.vue')
            },
        ]
    },
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

router.beforeEach((to, from, next) => {
    const token = localStorage.getItem("token");
    const isLoginPage = to.path === '/login';
    const isLoggedIn = !!token;
    const requiresAuth = to.matched.some(record => record.meta.requiresAuth);

    if (requiresAuth && !isLoggedIn) {
        // 如果需要鉴权且未登录，则跳转到登录页
        next('/login');
    } else if (isLoginPage && isLoggedIn) {
        // 如果已在登录状态且尝试访问登录页，则跳转到首页
        next('/index');
    } else if (!isLoginPage && !isLoggedIn && to.meta.requiresAuth) {
        // 如果未登录且尝试访问非登录页且该页需要鉴权，则跳转到登录页
        next('/login');
    } else {
        // 其他情况正常放行
        next();
    }

    // 如果需要动态添加路由且尚未添加，此处逻辑保持不变
    if (!store.state.menus.hasRoutes && isLoggedIn) {
        // ...你的动态添加路由逻辑
        axios.get("/sys/menu/nav", {
            headers: {
                Authorization: localStorage.getItem("token")
            }
        }).then(res => {
            // 拿到menuList
            store.commit("setMenuList", res.data.data.nav)

            // 拿到用户权限
            store.commit("setPermList", res.data.data.authoritys)

            console.log(store.state.menus.menuList)

            // 动态绑定路由
            let newRoutes = router.options.routes

            res.data.data.nav.forEach(menu => {
                if (menu.children) {
                    menu.children.forEach(e => {
                        // 转成路由
                        let route = menuToRoute(e)
                        // 把路由添加到路由管理中
                        if (route) {
                            newRoutes[0].children.push(route)
                        }
                    });
                }
            });

            console.log("newRoutes")
            console.log(newRoutes)
            router.addRoutes(newRoutes)

            store.commit("changeRouteStatus", true);
        })
    }
});

/*router.beforeEach((to, from, next) => {

    let hasRoute = store.state.menus.hasRoutes

    let token = localStorage.getItem("token")

    if(to.matched.some(record => record.meta.requiresAuth) && !token){
        next({path: '/login'});
    }else{
        next();
    }

    if (to.path === '/login') {
        if(token){
            next({path: '/index'})
        }else {
            next();
        }
    }else if (to.path === '/enroll') {
        next();  // 注册页面，无需权限，正常进入
    } else if (!token) {
        next({path: '/index'})
    } else if (token && !hasRoute) {
        axios.get("/sys/menu/nav", {
            headers: {
                Authorization: localStorage.getItem("token")
            }
        }).then(res => {

            console.log(res.data.data)

            // 拿到menuList
            store.commit("setMenuList", res.data.data.nav)

            // 拿到用户权限
            store.commit("setPermList", res.data.data.authoritys)

            console.log(store.state.menus.menuList)

            // 动态绑定路由
            let newRoutes = router.options.routes

            res.data.data.nav.forEach(menu => {
                if (menu.children) {
                    menu.children.forEach(e => {
                        // 转成路由
                        let route = menuToRoute(e)
                        // 把路由添加到路由管理中
                        if (route) {
                            newRoutes[0].children.push(route)
                        }
                    });
                }
            });

            console.log("newRoutes")
            console.log(newRoutes)
            router.addRoutes(newRoutes)

            hasRoute = true
            store.commit("changeRouteStatus", hasRoute);

        })
    }
        next()
})*/


// 导航转成路由
const menuToRoute = (menu) => {

    if (!menu.component) {
        return null
    }

    let route = {
        name: menu.name,
        path: menu.path,
        meta: {
            icon: menu.icon,
            title: menu.title
        }
    }
    route.component = () => import('@/views/' + menu.component + '.vue')

    return route
}

export default router
